require "Common/functions"

SpineEffectManager = {};
local this = SpineEffectManager;

local effectPool = {};
local effectPlaying = {};--正在播放的动画
local effectPoolRoot = nil;

function SpineEffectManager.init()
    effectPool = {};
end

function SpineEffectManager.destroy()
    this.clearAllEff();
end

function SpineEffectManager.createEffectPool(parent, obj, capacity, obj_name)
    effectPoolRoot = parent
    local objname = obj_name
    if objname == nil then
        objname = obj.name
    end
    if effectPool[objname] == nil then
        effectPool[objname] = {};

        for i = 1, capacity do
            local effgo = newObject(obj);
            if effectPoolRoot ~= nil then
                effgo.transform:SetParent(effectPoolRoot);
            end
            effgo:SetActive(false);
            table.insert(effectPool[objname], effgo);
        end
    end
end

function SpineEffectManager.getEffect(key)
    local eList = effectPool[key]
    if eList == nil then
        return nil
    end
    local go = table.remove(eList, 1)
    if go == nil then
        return nil;
    end
    go.gameObject:SetActive(true)
    return go
end

function SpineEffectManager.releaseEffect(go, key_name, fighterId, isCut)
    if HelperFunc.IsNull(go) then
        return
    end

    if effectPoolRoot ~= nil then
        go.transform:SetParent(effectPoolRoot);
    end
    go:SetActive(false);

    local key = nil
    if key_name == nil then
        local goName = go.name;
        local first = string.find(goName, "Clone")
        if first ~= nil then
            key = string.sub(goName, 1, first - 2)
        else
            key = goName;
        end
        -- print("SpineEffectManager.releaseEffect----------------------key_name:", key_name, "key:", key, "goName:", goName)
    else
        key = key_name
    end

    local eList = effectPool[key]
    if eList == nil then
        eList = {};
    end
    if isCut == 1 then
        SpineEffectManager.clearPlayingEffect(fighterId, key_name)
    end
    table.insert(eList, go);
    effectPool[key] = eList;
end

function SpineEffectManager.clearAllEff()
    for k, v in pairs(effectPool) do
        for _, eff in pairs(v) do
            destroy(eff);
        end
    end
    effectPool = {};
end

function SpineEffectManager.addPlayingEffect(fighterId, key, go)
    if effectPlaying[key] == nil then
        effectPlaying[key] = {}
    end
    effectPlaying[key][fighterId] = go;
end

function SpineEffectManager.getPlayingEffect(fighterId, key)
    --获取正在播放中的动画
    if effectPlaying[key] == nil then
        effectPlaying[key] = {}
    end
    return effectPlaying[key][fighterId];
end

function SpineEffectManager.clearPlayingEffect(fighterId, key)
    if effectPlaying[key] == nil then
        effectPlaying[key] = {}
        return ;
    end
    if effectPlaying[key][fighterId] ~= nil then
        effectPlaying[key][fighterId] = nil;
    end
end
